<?php

declare (strict_types=1);

namespace app\model;


use app\BaseModel;
use app\utils\JwtUtil;
use Exception;
use think\model\concern\SoftDelete;

use function myException;

class SystemUserModel extends BaseModel
{
    use SoftDelete;

    protected $autoWriteTimestamp = true;
    //软删除
    protected $deleteTime = 'delete_time';
    protected $hidden = ['delete_time', 'update_time'];
    protected $name = 'system_user';


    public function login($username, $password): string
    {
        try {
            // 查找身份，验证身份
            $user = $this->getOne([['username', '=', $username]]);
            if (empty($user)) {
                exception('用户不存在');
            }
            $jwt = [
                'password' => $password,
            ];
            //密码验证
            if ($user['password'] !== think_encrypt(JwtUtil::encode($jwt))) {
                exception('用户密码错误');
            }

            // 数据处理和令牌获取
            $time       = time();
            $login_time = date('Y-m-d H:i:s', $time);
            //登录事件
            self::update(['login_time' => $login_time, 'login_ip' => request()->ip()], ['id' => $user['id']]);

            // 令牌生成
            $admin_user_login_expire_time = getConfigs('system_config.admin_login_expire_time');
            $payload                      = [
                'uid'        => $user['id'],
                'signTime'   => $time,
                'expireTime' => $admin_user_login_expire_time + $time,
                'app_host'   => getConfigs('system_config.development_mode'),
            ];
            LoginLogModel::create([
                'account' => $username,
                'ip'      => request()->ip(),
                'notes'   => '登录成功',
                'status'  => 0,
            ]);

            return think_encrypt(JwtUtil::encode($payload));
        } catch (Exception $e) {
            LoginLogModel::create([
                'account' => $username,
                'ip'      => request()->ip(),
                'notes'   => $e->getMessage(),
                'status'  => 1,
            ]);
            myException($e->getMessage());
        }
    }


    public function checkToken($userToken): mixed
    {
        $result = ['code' => false];
        if (empty($userToken)) {
            $result['data'] = response('用户访问令牌缺失', 401);

            return $result;
        }
        $userToken = think_decrypt($userToken);
        $payload   = JwtUtil::decode($userToken);
        if (empty($payload) || empty($payload->uid) || empty($payload->signTime) || empty($payload->expireTime) || ! isset($payload->app_host)) {
            $result['data'] = response('用户访问令牌错误', 401);

            return $result;
        }
        if ($payload->app_host != getConfigs('system_config.domain_name')) {
            $result['data'] = response('用户访问令牌错误', 401);
        }

        if (time() >= $payload->expireTime) {
            $result['data'] = response('用户访问令牌过期', 401);

            return $result;
        }
        // 实时用户数据
        $user = $this->getOne([['id', '=', $payload->uid]]);
        //用户是否存在
        if (empty($user)) {
            $result['data'] = response('用户不存在', 401);

            return $result;
        }

        return ['code' => true, 'data' => $user];
    }
}